package com.newshub.business.service.impl;

import com.newshub.business.dto.SourceQueryDTO;
import com.newshub.business.entity.Source;
import com.newshub.business.mapper.SourceMapper;
import com.newshub.business.service.SourceService;
import com.newshub.logging.annotation.BusinessLog;
import com.newshub.logging.annotation.LogLevel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.HashMap;
import java.util.ArrayList;

/**
 * 新闻源服务实现类
 */
@Service
public class SourceServiceImpl implements SourceService {
    
    @Autowired
    private SourceMapper sourceMapper;
    
    @Override
    @BusinessLog(level = LogLevel.INFO, description = "分页查询新闻源")
    public List<Source> getSourcesByPage(SourceQueryDTO queryDTO) {
        return sourceMapper.selectByPage(queryDTO);
    }
    
    @Override
    public long countSourcesByPage(SourceQueryDTO queryDTO) {
        return sourceMapper.countByPage(queryDTO);
    }
    
    @Override
    @BusinessLog(level = LogLevel.INFO, description = "根据ID获取新闻源")
    public Source getSourceById(Integer id) {
        return sourceMapper.selectById(id);
    }
    
    @Override
    @BusinessLog(level = LogLevel.INFO, description = "根据代码获取新闻源")
    public Source getSourceByCode(String code) {
        return sourceMapper.selectByCode(code);
    }
    
    @Override
    @BusinessLog(level = LogLevel.INFO, description = "根据名称获取新闻源")
    public Source getSourceByName(String name) {
        return sourceMapper.selectByName(name);
    }
    
    @Override
    @Transactional
    @BusinessLog(level = LogLevel.INFO, description = "添加新闻源")
    public boolean addSource(Source source) {
        try {
            // 设置默认值
            if (source.getSortOrder() == null) {
                source.setSortOrder(0);
            }
            if (source.getStatus() == null) {
                source.setStatus(1); // 默认启用
            }
            
            // 设置时间
            LocalDateTime now = LocalDateTime.now();
            source.setCreatedAt(now);
            source.setUpdatedAt(now);
            
            // 插入数据
            int result = sourceMapper.insert(source);
            return result > 0;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
    
    @Override
    @Transactional
    @BusinessLog(level = LogLevel.INFO, description = "更新新闻源")
    public boolean updateSource(Source source) {
        try {
            // 设置更新时间
            source.setUpdatedAt(LocalDateTime.now());
            
            // 更新数据
            int result = sourceMapper.updateById(source);
            return result > 0;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
    
    @Override
    @Transactional
    @BusinessLog(level = LogLevel.WARN, description = "删除新闻源")
    public boolean deleteSource(Integer id) {
        try {
            int result = sourceMapper.deleteById(id);
            return result > 0;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
    
    @Override
    @Transactional
    @BusinessLog(level = LogLevel.WARN, description = "批量删除新闻源")
    public boolean deleteBatchSources(List<Integer> ids) {
        try {
            int result = sourceMapper.deleteBatchByIds(ids);
            return result > 0;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
    
    @Override
    @Transactional
    public boolean updateSourceStatus(Integer id, Integer status) {
        try {
            int result = sourceMapper.updateStatusById(id, status);
            return result > 0;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
    
    @Override
    public List<Source> getAllEnabledSources() {
        return sourceMapper.selectAllSources().stream()
                .filter(source -> source.getStatus() == 1)
                .toList();
    }
    
    @Override
    public List<Source> getSourcesByRegionId(Integer regionId) {
        return sourceMapper.selectByRegionId(regionId);
    }
    
    @Override
    public List<Source> getAllSources() {
        return sourceMapper.selectAllSources();
    }

    // ==================== 统计功能实现 ====================
    
    @Override
    public Map<String, Object> getSourceDistributionStats() {
        Map<String, Object> result = new HashMap<>();
        
        try {
            // 获取信源分布数据
            List<Map<String, Object>> sourceStats = sourceMapper.selectSourceDistribution();
            
            // 提取信源名称和新闻数量
            List<String> sourceNames = new ArrayList<>();
            List<Integer> newsCounts = new ArrayList<>();
            List<Map<String, Object>> pieData = new ArrayList<>();
            
            for (Map<String, Object> item : sourceStats) {
                String sourceName = item.get("sourceName").toString();
                Integer newsCount = Integer.valueOf(item.get("newsCount").toString());
                
                sourceNames.add(sourceName);
                newsCounts.add(newsCount);
                
                // 构建饼图数据
                Map<String, Object> pieItem = new HashMap<>();
                pieItem.put("name", sourceName);
                pieItem.put("value", newsCount);
                pieData.add(pieItem);
            }
            
            result.put("sourceNames", sourceNames);
            result.put("newsCounts", newsCounts);
            result.put("pieData", pieData);
            result.put("total", newsCounts.stream().mapToInt(Integer::intValue).sum());
            
        } catch (Exception e) {
            result.put("error", "获取信源分布数据失败: " + e.getMessage());
        }
        
        return result;
    }
}